package cn.com.nou.common.upload;

import com.github.tobato.fastdfs.domain.fdfs.MetaData;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;

import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@Service
public class UploadClientImpl  implements UploadClient{
	private static final Logger logger = LoggerFactory.getLogger(UploadClientImpl.class);

	private FastFileStorageClient client;

	public UploadClientImpl(FastFileStorageClient client) {
		this.client = client;
	}

	@Override
	public String uploadFile(MultipartFile file) throws IOException {
		String name = file.getOriginalFilename();
		String ext = FilenameUtils.getExtension(name);
		try (InputStream inputStream = file.getInputStream()) {
			StorePath storePath = client.uploadFile(inputStream, file.getSize(), ext, null);
			return storePath.getFullPath();
		} catch (Exception e) {
			throw e;
		}
	}

	@Override
	public List<String> uploadFiles(List<MultipartFile> files) throws IOException {
		StorePath storePath = new StorePath();
		List<String> pathList = new ArrayList();
		for (int i = 0; i < files.size(); i++) {
			String name = files.get(i).getOriginalFilename();
			String ext = FilenameUtils.getExtension(name);
			InputStream inputStream = files.get(i).getInputStream();
			storePath = client.uploadFile(inputStream, files.get(i).getSize(), ext, null);
			String fullPath = storePath.getFullPath();
			pathList.add(fullPath);
		}
		return pathList;
	}

	@Override
	public String uploadFile(InputStream inputStream, long fileSize, String fileExtName, Set<MetaData> metaDataSet)
			throws IOException {
		logger.info("inputStream::::::::::" + inputStream.toString());
		logger.info("fileExtName::::::::::" + fileExtName);
		StorePath storePath = client.uploadFile(inputStream, fileSize, fileExtName, null);
		return storePath.getFullPath();
	}

	@Override
	public void deleteFile(String filePath) {
		client.deleteFile(filePath);
	}

	@Override
	public byte[] downloadFile(String fileUrl) {
		String group = fileUrl.substring(0, fileUrl.indexOf("/"));
		String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
		DownloadByteArray downloadByteArray = new DownloadByteArray();
		byte[] bytes = client.downloadFile(group, path, downloadByteArray);
		return bytes;
	}
}
